package cn.jjxx.shiro.session.core;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;

/**
 * Session序列化工具类，使用该类将session转化为byte[],保存到redis中
 *@Title ShiroSessionConvertUtil.java
 *@description TODO
 *@time 2020年7月16日 下午12:25:58
 *@author YAOXIONG
 *@version 1.0
 *
 */
public class ShiroSessionConvertUtil {


	/**
	 * 把session对象转化为byte数组
	 * @param session
	 * @return
	 */
	public static byte[] sessionToByte(Session session){
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		byte[] bytes = null;
		try {
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(session);
			bytes = bo.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 把byte数组还原为session
	 * @param bytes
	 * @return
	 */
	public static Session byteToSession(byte[] bytes){
		ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
		ObjectInputStream in;
		Session session = null;
		try {
			in = new ObjectInputStream(bi);
			session = (SimpleSession) in.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return session;
	}
	
	
	/**
	 * 
	*@Title ShiroSessionConvertUtil.java
	*@description TODO
	*@time 2020年8月25日 下午3:28:49
	*@author YAOXIONG
	*@version 1.0
	*
	 */
	public static byte[] objectToByte(Object obj){
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		byte[] bytes = null;
		try {
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(obj);
			bytes = bo.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 
	*@Title ShiroSessionConvertUtil.java
	*@description TODO
	*@time 2020年8月25日 下午3:29:16
	*@author YAOXIONG
	*@version 1.0
	*
	 */
	public static Object byteToObejct(byte[] bytes){
		ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
		ObjectInputStream in;
		Object obj = null;
		try {
			in = new ObjectInputStream(bi);
			obj = in.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	
}
